package com.example.udptest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.share.clipshare.R;

public class MainActivity extends Activity {
	private ClipboardManager  clipboard=null;
	private Thread t=null;
	
	//private WifiManager.MulticastLock lock;
	private WifiManager wifi;
	private Button okButton;
	private UdpSend udpsend;
	private EditText text;
	private EditText sendText;
	private Button sendButton;
	private TextView tview;
	private static SharedPreferences sp;
	private String tmpip;
	private Editor editor;
    @SuppressLint("NewApi") 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        wifi=(WifiManager)this.getSystemService(WIFI_SERVICE);
        udpsend=new UdpSend(wifi);
        udpsend.setMessage(clipboard.getText().toString());
        t=new Thread(udpsend);
        t.start();
        sp=PreferenceManager.getDefaultSharedPreferences(this);      
        this.okButton = (Button)this.findViewById(R.id.clip);
        this.sendText=(EditText)this.findViewById(R.id.send);
        //this.sendText.setBackgroundColor(Color.GRAY);
        sendText.requestFocus();
        this.sendText.setTextColor(Color.GREEN);
        this.sendButton = (Button)this.findViewById(R.id.go);
        this.text=(EditText)this.findViewById(R.id.addr);
        this.text.setTextColor(Color.GREEN);
        
        String ipstr=sp.getString("ip", "");
        if(!ipstr.equalsIgnoreCase("")){
        	this.text.setText(ipstr);
        }
        listenEditText();
        this.okButton.setOnClickListener(new OnClickListener() {
        
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				udpsend.setMessage(clipboard.getText().toString());
				t=new Thread(udpsend);
				t.start();
		      
			}
        });
        sendTexts();
    }
    public void listenEditText(){
    	this.text.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				tmpip=text.getText().toString();
				udpsend.setIp(tmpip);
			}
    		
    	});
    	this.text.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				tmpip=text.getText().toString();
				if(tmpip==null){
					udpsend.setIp("255.255.255.255");
					return;
				}
				Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
		        Matcher matcher = pattern.matcher(tmpip);
		        if(matcher.matches()){
		        	editor = sp.edit();
		        	editor.putString("ip", tmpip);
		        	editor.commit();
		        	udpsend.setIp(tmpip);
		        }
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
    		
    	});
    }
    public void sendTexts(){
    	this.sendButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String tmptext=sendText.getText().toString();
				udpsend.setMessage(tmptext);
				t=new Thread(udpsend);
			    t.start();
			}
    		
    	});
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public class UdpSend implements Runnable{
    	private String message=null;
    	private WifiManager.MulticastLock lock; 
    	DatagramSocket client;
    	private String ip;
    	UdpSend(WifiManager manager){
    		this.lock=manager.createMulticastLock("udpwifi");
    		ip="255.255.255.255";
    	}
    	public void setMessage(String msg){
    		message=msg;
    	}
    	public void setIp(String addr){
    		ip=addr;
    	}
    	public void send(){
    		
    		try {
    			
				client=new DatagramSocket();
				client.setBroadcast(true);
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		InetAddress addr=null;
			try {
				addr = InetAddress.getByName(ip);
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		byte[] buffer=message.getBytes();
    		DatagramPacket packet = new DatagramPacket(buffer,  
                    buffer.length,addr,8082); 
    		try {
				client.send(packet);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		client.close();
    	}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			send();
		}
    	
    }
}
